<template>
  <div :id="id" class="editor"></div>
</template>

<script setup name="editor">
  import { useStore } from "@/hooks/store/useStore"

  const { base } = useStore()

  import EditorJS from '@editorjs/editorjs';
  import Header from '@editorjs/header';
  import List from '@editorjs/list';
  import Image from '@editorjs/image';
  import Table from '@editorjs/table';
  import zh from './i18n.json'

  const props = defineProps({
    content: {
      type: String,
      default: "",
    },
  })

  const id = 'editor' + Math.random()
  const data = ref()
  const editor = ref(null)

  onMounted(() => {
    editor.value = new EditorJS({
      holder: id,
      placeholder: '请输入内容',
      i18n: { messages: zh },
      tools: {
        header: {
          class: Header,
          inlineToolbar: true,
        },
        image: {
          class: Image,
          inlineToolbar: true,
          config: {
            field: 'file',
            types: 'image/*, .mkv, .mp4, .avi, .mov, .wmv',
            actions: [],
            additionalRequestHeaders: {
              Authorization: 'Bearer ' + base.token,
            },
            endpoints: {
              byFile: $http.adornUrl('/file/editor'), // 上传图片接口
            }
          }
        },
        table: {
          class: Table,
          inlineToolbar: true
        }
      },
      onChange: (api, event) => {
        editor.value.save().then((res) => {
          data.value = JSON.stringify(res)
        });
      },
      onReady: () => {
        editor.value.save().then((res) => {
          data.value = JSON.stringify(res)
        });
      }
    })
  })


  // 初始化内容
  watch(() => props.content, (value, oldValue) => {
    setTimeout(() => {
      editor.value.render(JSON.parse(value));
      data.value = value
    }, 1000);
  })


  // 使用defineExpose暴露content
  defineExpose({
    data
  });

</script>

<style>
  .editor {
    width: 800px;
    padding: 20px 20px;
    white-space: normal;
    word-wrap: break-word;
    word-break: break-all;
    border: 1px solid #bbb;
  }

  .ce-popover-item[data-item-name="withBorder"],
  .ce-popover-item[data-item-name="withBackground"],
  .ce-popover-item[data-item-name="stretched"] {
    display: none;
  }
</style>
